package spring.mvc.hibernate;

import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import entities.User;
import user.UserDAO;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	@Autowired
	private UserDAO userDao;
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */

	@Transactional
	@RequestMapping(value="/")
	public ModelAndView home(){
		List<User> listUsers = userDao.list();
		ModelAndView model = new ModelAndView("home");
		model.addObject("userList", listUsers);
		return model;
	}
	
	@Transactional
	@RequestMapping(value="new", method= RequestMethod.GET)
	public ModelAndView login(){
		ModelAndView model = new ModelAndView("login");
		model.addObject("user", new User());
		return model;
	}
	
	@Transactional
	@RequestMapping(value="save", method=RequestMethod.POST)
	public ModelAndView save(@ModelAttribute User user){
		userDao.saveOrUpdate(user);
		return new ModelAndView("redirect:/");
	}
	
	@Transactional
	@RequestMapping(value="edit", method=RequestMethod.GET)
	public ModelAndView edit(HttpServletRequest request){
		int id = Integer.parseInt(request.getParameter("id"));
		User user = userDao.get(id);
		ModelAndView model = new ModelAndView("login");
		model.addObject("user", user);
		return model;
	}
	
	@Transactional
	@RequestMapping(value="delete" , method = RequestMethod.GET)
	public ModelAndView delete(HttpServletRequest request){
		int id = Integer.parseInt(request.getParameter("id"));
		User user = userDao.get(id);
		userDao.delete(user);
		return new ModelAndView("redirect:/");
	}
}
